<template>
    <div class="wrap">
        <div class="search-container">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="字典" prop="name">
                    <div>{{ typeName }}</div>
                </el-form-item>
                <el-form-item label="名称" prop="label">
                    <el-input
                            v-model="queryParams.keywords"
                            placeholder="字典名称"
                            clearable
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery()">
                        <i-ep-search/>
                        搜索
                    </el-button>
                    <el-button @click="resetQuery()">
                        <i-ep-refresh/>
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-card shadow="never">
            <template #header>
                <el-button
                        v-hasPerm="['sys:dict:add']"
                        type="success"
                        @click="handleAdd()"
                ><i-ep-plus />新增</el-button
                >
                <el-button type="primary"
                           @click.stop="handleSave"
                ><i-ep-delete />保存</el-button>
                <el-button
                        v-hasPerm="['sys:dict:delete']"
                        type="danger"
                        :disabled="ids.length === 0"
                        @click="handleDelete()"
                ><i-ep-delete />删除</el-button
                >
            </template>

            <!-- 数据表格 -->
            <el-table
                    id="dicDetail"
                    class="dicDetail"
                    ref="dicDetail"
                    v-loading="loading"
                    :data="dictList"
                    border
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="50" />
                <el-table-column label="字典名称">
                    <template #default="{row}">
                        <span>{{row.name}}</span>
<!--                        <el-input-->
<!--                                size="mini"-->
<!--                                v-model="scope.row.name"-->
<!--                                :class="scope.row.repeactName ? 'childred' : ''"-->
<!--                                @blur="handleBlur($event, scope.row, 'name', $el)"-->
<!--                        ></el-input>-->
                    </template>
                </el-table-column>
                <el-table-column label="字典值" prop="value" />
                <el-table-column label="状态" align="center">
                    <template #default="{ row }">
                        <el-tag v-if="row.status === 1" type="success">启用</el-tag>
                        <el-tag v-else type="info">禁用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="字典值" prop="remark" />
                <el-table-column label="拖拽" align="center">
                    <template>
                        <i class="el-icon-sort"></i>
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                    v-if="total > 0"
                    v-model:total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="handleQuery"
            />
        </el-card>
    </div>
</template>

<script setup lang="ts">
    import {
        getDictPage,
        getDictFormData,
        addDict,
        updateDict,
        deleteDict, deleteDictTypes,
    } from "@/api/dict";
    import {DictPageVO, DictQuery, DictForm} from "@/api/dict/types";
    import Sortable, {SortableEvent} from "sortablejs";
    const props = defineProps({
        typeCode: {
            type: String,
            default: () => {
                return "";
            },
        },
        typeName: {
            type: String,
            default: () => {
                return "";
            },
        },
    });
    watch(
        () => props.typeCode,
        (newVal: string) => {
            queryParams.typeCode = newVal;
            resetQuery();
        }
    );
    const loading = ref(false);
    const queryFormRef = ref(ElForm);
    const total = ref(0);
    const queryParams = reactive<DictQuery>({
        pageNum: 1,
        pageSize: 10,
        keywords: '',
        typeCode: props.typeCode,
    });
    const dictList = ref<DictPageVO[]>();
    const ids = ref<number[]>([]);
    // const deleteDisabled = computed()


    /**
     * 查询
     */
    function handleQuery() {
        if (queryParams.typeCode) {
            loading.value = true;
            getDictPage(queryParams)
                .then(({ data }) => {
                    dictList.value = data.list.map(item => {
                        item.repeatValue = false;
                        item.repeactName = false;
                    })
                    total.value = data.total;
                })
                .finally(() => (loading.value = false));
        }
    }

    /**
     * 重置查询
     */
    function resetQuery() {
        queryFormRef.value.resetFields();
        queryParams.pageNum = 1;
        handleQuery();
    }
    /**
     * 判断是否重复
     */
    function handleBlur(e: any, row: DictForm, key: string) {
        if (['name', 'value'].includes(key)) {
            const map = {};
            dictList.value.forEach((item: any, index: number) => {
                if (map[item[key]]) map[item[key]].push(index);
                else map[item[key]] = [index];
            });
            for (const k in map) {
                if (map[k].length > 1) {
                    map[k].forEach((f) => {
                        dictList.value[f][`repeat${key}`] = true;
                    });
                } else {
                    dictList.value[map[k][0]][`repeat${key}`] = false;
                }
            }
        }
        let isFlag = dictList.value.some((item: any) => {
            return item.repeactName || item.repeatValue;
        });
        if (isFlag) {
            ElMessage.warning("请选择要删除的字典详情数据!");
            return false;
        }
        if (row.id) {
            let params = {...row};
            updateDict(params).then((res) => {
                // this.getDicDetail();
            });
        }
    }
    function handleAdd() {
        let tmpObj = {
            name: "",
            value: "",
            sort: dictList.value.length,
            remark: "",
            repeatValue: false,
            repeatName: false,
        }
        dictList.value.push(tmpObj)
    }
    /**
     * 删除
     */
    function handleDelete() {
        const dictIds = ids.value.join(",");
        if (!ids.value.length) {
            ElMessage.warning('请选择要删除的字典详情数据！');
            return false;
        }
        ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            deleteDict(dictIds).then(() => {
                ElMessage.success("删除成功");
                resetQuery();
            });
        });
    }
    /** 行复选框选中  */
    function handleSelectionChange(selection: any) {
        ids.value = selection.map((item: any) => item.id);
    }
    // 行拖拽
    function rowDrag () {
        // 要拖拽元素的父容器
        const tbody = document.querySelector(
            ".dicDetail .el-table__body-wrapper tbody"
        );
        if (!tbody) return;
        Sortable.create(tbody as HTMLElement, {
            //  可被拖拽的子元素
            draggable: ".dicDetail .el-icon-sort",
            onEnd(event: SortableEvent) {
                if (event.oldIndex !== undefined && event.newIndex !== undefined) {
                    const currRow = list.value.splice(event.oldIndex, 1)[0];
                    list.value.splice(event.newIndex, 0, currRow);
                }
            },
        });
    };
    /** 保存  */
    function handleSave() {
        let hasEmpty = dictList.value.some((item: any) => !(item.name && item.value));
        let isFlag = dictList.value.some((item: any) => {
            return item.repeatName || item.repeatValue;
        });

        if (hasEmpty) {
            ElMessage.warning('字典标签或者值数据不能为空！');
            return false;
        } else if (isFlag) {
            ElMessage.warning('字典标签或者值不能重复！');
            return false;
        } else {
            addDic();
        }
    }
    /** 新增字典详情  */
    function addDic() {
        Promise.all(
            dictList.value.map((item) => {
                if (!item.hasOwnProperty("id")) {
                    return new Promise((resolve, reject) => {
                        addDict(item).then((res) => {
                            resolve(res);
                        }).catch((error) => {
                            reject(error)
                        })
                    })
                }

            })
        ).then((res) => {
            ElMessage.success('添加成功！');
            handleQuery();
        })
    }


</script>

<style scoped>

</style>
